package com.keyin;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.webkit.WebView;
import android.widget.Toast;

import com.keyin.protocol.CacheImageProtocol;
import com.keyin.protocol.MagazineIndexCache;
import com.keyin.protocol.Periodical;
import com.keyin.protocol.Protocol;
import com.keyin.protocol.ProtocolHelper;

public class ReadMagazineActivity extends BaseActivity {

	private Periodical periodical;
	private int page;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setContentView(R.layout.a_read);
		onNewIntent(getIntent());
	}

	@Override
	protected void onNewIntent(Intent intent) {
		super.onNewIntent(intent);

		String peridocalId = intent.getExtras().getString("peridocal_id");
		periodical = MagazineIndexCache.get(peridocalId);
		if (periodical == null) {
			new AlertDialog.Builder(this).setTitle("提示").setMessage(
					"杂志文件出错，请重新下载").setPositiveButton("取消",
					new DialogInterface.OnClickListener() {

						@Override
						public void onClick(DialogInterface dialog, int which) {
							finish();
						}
					}).show();
		}

		page = intent.getExtras().getInt("page");

		Protocol p = ProtocolHelper.getPeriodical(getApplicationContext(),
				peridocalId, page);
		String url = p.getUrl();
		url = CacheImageProtocol.encode(url);

		WebView web = (WebView) findViewById(R.id.web_view);

		String html = "<html><body>" + "<img src=\"" + url
				+ "\"/></body></html>";

		web.loadDataWithBaseURL("file:///mnt/sdcard/keyin/", html, "text/html",
				"utf-8", null);
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		menu.add(0, 0, 0, "上一页");
		menu.add(0, 1, 0, "下一页");
		return super.onCreateOptionsMenu(menu);
	}

	@Override
	public boolean onMenuItemSelected(int featureId, MenuItem item) {
		switch (item.getItemId()) {
		case 0: {
			if (page == 1) {
				Toast.makeText(this, "已经是第一页了", Toast.LENGTH_SHORT).show();
			} else {
				Intent i = new Intent(this, ReadMagazineActivity.class);
				i.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
				i.putExtra("page", --page);
				i.putExtra("peridocal_id", periodical.periodical_id);
				startActivity(i);
			}
		}
			break;
		case 1: {
			if (page == periodical.pages) {
				Toast.makeText(this, "已经是最后一页了", Toast.LENGTH_SHORT).show();
			} else {
				Intent i = new Intent(this, ReadMagazineActivity.class);
				i.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
				i.putExtra("page", ++page);
				i.putExtra("peridocal_id", periodical.periodical_id);
				startActivity(i);;
			}
		}
			break;
		}
		return super.onMenuItemSelected(featureId, item);
	}
}
